<template>
  <div class="self_adaption">
    <div class="g-container">
      <div class="other">
        <p class="main_text">发票管理</p>
      </div>
      <!-- 搜索 -->
      <div class="g-search" ref="searchBox">
        <!-- 时间选择区域 -->
        <div class="demo-date-picker">
          <div class="block">
            <span class="demonstration">商品创建时间：</span>
            <el-date-picker
              v-model="searchValue.startAt"
              type="date"
              placeholder="开始时间"
              @change="startTime"
              :clearable="false"
              :default-time="defaultTime(0, 0, 0)" />
            <span class="demonstration" style="display: inline-block; font-size: 12px; color: #898989; margin: 20px"
              >至</span
            >
            <el-date-picker
              v-model="searchValue.endAt"
              type="date"
              placeholder="结束时间"
              @change="endTime"
              :clearable="false"
              :default-time="defaultTime1(23, 59, 59)" />

            &emsp;
            <el-radio-group v-model="radio" class="ml-4" @change="radioSelect">
              <el-radio label="1" size="large">今天</el-radio>
              <el-radio label="2" size="large">昨天</el-radio>
              <el-radio label="3" size="large">近三天</el-radio>
              <el-radio label="4" size="large">近一周</el-radio>
              <el-radio label="5" size="large">近一个月</el-radio>
              <el-radio label="6" size="large">近三个月</el-radio>
              <el-radio label="7" size="large">近一年</el-radio>
            </el-radio-group>
          </div>
        </div>
        <!-- 信息区域 -->
        <div class="all_select">
          <!-- 订单编号 -->
          <div class="input_valye">
            <span class="demonstration">订单编号：</span>
            <input
              type="text"
              class="input"
              placeholder="请输入订单编号"
              v-model="searchValue.orderSn"
              @keyup.enter="search" />
          </div>
          <!-- 发票类型 -->
          <div class="input_valye">
            <span class="demonstration">发票类型：</span>
            <el-select v-model="searchValue.type" class="m-2" placeholder="请选择抬头类型" @change="search">
              <el-option v-for="item in Type_options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
          <!-- 抬头类型 -->
          <div class="input_valye">
            <span class="demonstration">抬头类型：</span>
            <el-select v-model="searchValue.riseType" class="m-2" placeholder="请选择抬头类型" @change="search">
              <el-option v-for="item in riseType_options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <!-- 底部按钮区域 -->
        <div class="bottom_btn">
          <el-button class="solid" @click="search">查询</el-button>
          <el-button class="hollow" @click="reset">重置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table">
        <!-- 表格导航栏 -->
        <div class="nav">
          <ul class="nav_ul">
            <li v-for="(item, index) in nav_list" :key="index" :class="item.class" @click="navChange(item)">
              <span class="nav_lis">{{ item.text }}</span>
            </li>
          </ul>
        </div>
        <!-- 表格区域 -->
        <el-table
          :data="tableData"
          style="width: 100%"
          :row-class-name="tableRowClassName"
          :header-cell-style="{
            'text-align': 'center',
            background: '#F2F7FC !important',
          }"
          :show-overflow-tooltip="true"
          border>
          <el-table-column type="selection" width="40" />
          <el-table-column prop="orderSn" label="订单编号" width="180" align="center" />
          <!-- <el-table-column prop="invoiceSn" label="发票编号" width="100" align="center" /> -->
          <el-table-column prop="type" label="发票类型" width="100" align="center">
            <template #default="item">
              <span v-if="item.row.type === 0">普票</span>
              <span v-else>专票</span>
            </template>
          </el-table-column>
          <el-table-column prop="riseType" label="抬头类型" width="100" align="center">
            <template #default="item">
              <span v-if="item.row.riseType === 0">个人</span>
              <span v-else>单位</span>
            </template>
          </el-table-column>
          <el-table-column prop="invoiceHeader" label="发票抬头" align="center" />
          <el-table-column prop="price" label="发票金额" align="center" />
          <el-table-column prop="status" label="发票状态" width="100" align="center">
            <template #default="item">
              <span v-if="item.row.status === 0">未处理</span>
              <span v-else>已处理</span>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="开票时间" width="180" align="center" />
          <el-table-column prop="createPerson" label="创建人姓名" width="120" align="center" />
          <el-table-column prop="phone" label="创建人电话" width="140" align="center" />
          <el-table-column prop="email" label="创建人邮箱" width="120" align="center" />
          <el-table-column label="操作" width="200" class="operation">
            <template #default="item">
              <div class="table_btn">
                <el-button size="small" class="none" @click="invoiceLook(item.row)" v-if="roleList.read"
                  >查看</el-button
                >
                <el-button
                  size="small"
                  class="none"
                  v-if="item.row.status === 0 && roleList.write"
                  @click="uploadFile(item.row)"
                  >上传</el-button
                ><br />
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <smartPager
          v-model:current-page="searchValue.page"
          v-model:page-size="searchValue.rows"
          :total="total"
          @change="pageChange" />
      </div>
      <!-- 查看发票 -->
      <el-form ref="ruleFormRef" :model="invoiceDate" label-width="100px" label-position="left" v-if="showInvoice">
        <div class="look_invoice">
          <!-- 商品基本信息 -->
          <div class="title1">
            <div class="title_mes">
              <el-icon size="20" color="#fff"><Edit /></el-icon>&nbsp;发票信息
            </div>
            <div class="close" @click="maskBtn1">✖</div>
          </div>
          <div class="content1" style="height: calc(100% - 80px); margin-top: 20px; overflow-y: scroll">
            <el-form-item label="订单编号:" prop="name">
              <el-input v-model="invoiceDate.orderSn" class="form_input" />
              <span id="input_hint"></span>
            </el-form-item>
            <el-form-item label="发票类型:" prop="unit">
              <el-select v-model="invoiceDate.type" class="m-2" placeholder="请选择发票类型">
                <el-option v-for="item in Type_options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="抬头类型:" prop="unit">
              <el-select v-model="invoiceDate.riseType" class="m-2" placeholder="请选择抬头类型">
                <el-option v-for="item in riseType_options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="发票抬头:" prop="name">
              <el-input v-model="invoiceDate.invoiceHeader" class="form_input" />
              <span id="input_hint"></span>
            </el-form-item>
            <el-form-item label="开票金额:" prop="name">
              <el-input v-model="invoiceDate.price" class="form_input" />
              <span id="input_hint"></span>
            </el-form-item>
            <el-form-item label="发票状态:" prop="unit">
              <el-select v-model="invoiceDate.status" class="m-2" placeholder="请选择发票状态">
                <el-option v-for="item in status_options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="开票时间:" prop="name">
              <el-input v-model="invoiceDate.createdAt" class="form_input" />
              <span id="input_hint"></span>
            </el-form-item>
            <el-form-item label="创建人姓名:" prop="name">
              <el-input v-model="invoiceDate.createPerson" class="form_input" />
              <span id="input_hint"></span>
            </el-form-item>
            <el-form-item label="创建人电话:" prop="name">
              <el-input v-model="invoiceDate.phone" class="form_input" />
              <span id="input_hint"></span>
            </el-form-item>
            <el-form-item label="创建人邮箱:" prop="name">
              <el-input v-model="invoiceDate.email" class="form_input" />
              <span id="input_hint"></span>
            </el-form-item>
            <el-form-item label="发票:" prop="name">
              <span v-if="invoiceDate.status == 0" style="color: #9e9e9e">暂未上传任何发票</span>
              <div v-else>
                <el-icon color="#7e7e7e" size="18"> <Document /> </el-icon>&emsp;<a
                  :href="fileList[0].url"
                  class="link"
                  style="color: #484848"
                  >{{ fileList[0].name }}</a
                >
              </div>
            </el-form-item>
            <div style="height: 60px"></div>
          </div>
        </div>
      </el-form>
      <div class="look_invoice1" v-if="uploadShow">
        <!-- 商品基本信息 -->
        <div class="title1">
          <div class="title_mes">
            <el-icon size="20" color="#fff"><Edit /></el-icon>&nbsp;发票信息
          </div>
          <div class="close" @click="maskBtn1">✖</div>
        </div>
        <div class="content1 content_box" style="margin-top: 20px">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            multiple
            :limit="1"
            v-model:file-list="fileList"
            :on-change="handleChange"
            :auto-upload="false">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖拽到此处，或<em>点击上传</em></div>
            <!-- <template #tip>
              <div class="el-upload__tip">
                jpg/png files with a size less than 500kb
              </div>
            </template> -->
          </el-upload>
          <div class="btn_center">
            <el-button class="hollow" @click="maskBtn1">取消</el-button>
            <el-button class="solid" @click="invoiceSure">确认</el-button>
          </div>
          <div style="height: 60px"></div>
        </div>
      </div>
      <!-- 遮罩层 -->
      <div id="mask1" v-if="mask" @click="maskBtn1"></div>
    </div>
  </div>
</template>
<script setup lang="ts">
import {ref, onMounted, onBeforeUnmount} from 'vue';
import {UploadFilled, Document} from '@element-plus/icons-vue';

import type {UploadInstance, UploadProps, UploadUserFile} from 'element-plus';
import {RequestInvoicesearch, RequestInvoiceUpload, RequestInvoiceStatus} from '@/api/path/index.js';

import {Warning, Edit} from '@element-plus/icons-vue';
import useAuthorize from '@/hooks/authorize';
let roleList = useAuthorize();

const uploadShow = ref(false); //上传发票显示
const mask = ref(false); //遮罩层显示
import moment from 'moment';
const radio = ref(''); //单选按钮
const showInvoice = ref(false); //控制组件显示
const total = ref(0); //发票总数
const tableData = ref([]); //发票数组
const shopId = Number(localStorage.getItem('ShopId'));
const defaultTime = (H: any, M: any, S: any) => {
  var now = new Date();
  now.setHours(H);
  now.setMinutes(M);
  now.setSeconds(S);
  return now;
};
const defaultTime1 = (H: any, M: any, S: any) => {
  var now = new Date();
  now.setHours(H);
  now.setMinutes(M);
  now.setSeconds(S);
  return now;
};
onMounted(() => {
  rquestInvoiceList();
  handleResize();
  window.addEventListener('resize', handleResize);
});
const searchBox = ref();
const tablelistHeight = ref();
const handleResize = () => {
  const searchBoxHeight = searchBox.value.clientHeight;
  tablelistHeight.value = 110 + searchBoxHeight + 'px';
  console.log('Search Box height11111111111111111111111111111:', searchBoxHeight);
};

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});

const nav_list = ref([
  {
    class: ['navlist', 'nav_li'],
    text: '全部',
    status: '',
    num: 0,
  },
  {
    class: ['nav_li'],
    text: '待处理',
    status: 0,
    num: 0,
  },
  {
    class: ['nav_li'],
    text: '已处理',
    status: 1,
    num: 0,
  },
]);

const invoiceDate = ref<any>({
  orderSn: '',
  type: '',
  riseType: '',
  invoiceHeader: '',
  status: '',
  createdAt: '',
  createPerson: '',
  phone: '',
  email: '',
  price: '',
});
/**
 * 抬头类型
 */
const riseType_options = [
  {
    value: 0,
    label: '个人',
  },
  {
    value: 1,
    label: '单位',
  },
];
/**
 * 发票类型
 */
const Type_options = [
  {
    value: 0,
    label: '普票',
  },
  {
    value: 1,
    label: '专票',
  },
];
/**
 * 发票状态
 */
const status_options = [
  {
    value: 0,
    label: '待处理',
  },
  {
    value: 1,
    label: '已处理',
  },
];

/**
 * 获取发票信息
 */
const rquestInvoiceList = async () => {
  const a = await RequestInvoicesearch(searchValue.value);
  console.log('获取成功', a.resultObj.invoices);
  tableData.value = a.resultObj.invoices;
  total.value = a.resultObj.totalCount;
};
/**
 * 表格导航栏点击切换
 */
const navChange = (item: any) => {
  for (let i = 0; i < nav_list.value.length; i++) {
    const filteredClasses = nav_list.value[i].class.filter((className) => className !== 'navlist');
    nav_list.value[i].class = filteredClasses;
  }
  item.class.push('navlist');
  searchValue.value.status = item.status;
  searchValue.value.page = 1;
  rquestInvoiceList();
};
/**
 * 分页
 */
const pageChange = async (val: number) => {
  rquestInvoiceList();
};
/**
 * 时间范围单选按钮
 */
const radioSelect = () => {
  searchValue.value.startAt = '';
  searchValue.value.endAt = '';
  var now = new Date();
  now.setHours(0);
  now.setMinutes(0);
  now.setSeconds(0);
  var now1 = new Date();
  now1.setHours(23);
  now1.setMinutes(59);
  now1.setSeconds(59);
  if (radio.value === '1') {
    searchValue.value.startAt = moment(now).format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '2') {
    searchValue.value.startAt = moment(now).subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '3') {
    searchValue.value.startAt = moment(now).subtract(3, 'days').format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '4') {
    searchValue.value.startAt = moment(now).subtract(7, 'days').format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '5') {
    searchValue.value.startAt = moment(now).subtract(1, 'months').format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '6') {
    searchValue.value.startAt = moment(now).subtract(3, 'months').format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  } else {
    searchValue.value.startAt = moment(now).subtract(1, 'years').format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  }
  search();
};

/**
 * 表格颜色区分
 */
const tableRowClassName = ({row, rowIndex}: any) => {
  if (rowIndex % 2 !== 0) {
    return 'warning-row';
  }
};
/**
 * 搜索值
 */
const searchValue = ref({
  startAt: '',
  endAt: '',
  orderSn: '',
  type: '',
  riseType: '',
  status: '',
  page: 1,
  rows: 10,
  shopId: shopId,
});
/**
 * 点击重置
 */
const reset = () => {
  searchValue.value = {
    startAt: '',
    endAt: '',
    orderSn: '',
    type: '',
    riseType: '',
    status: '',
    page: 1,
    rows: 10,
    shopId: shopId,
  };
  radio.value = '';
  rquestInvoiceList();
};
// 开始时间
const startTime = () => {
  searchValue.value.startAt.setHours(0);
  searchValue.value.startAt.setMinutes(0);
  searchValue.value.startAt.setSeconds(0);
  searchValue.value.startAt = moment(searchValue.value.startAt).format('yyyy-MM-DD HH:mm:ss');
  radio.value = '';
  search();
};
// 结束时间
const endTime = () => {
  searchValue.value.endAt.setHours(23);
  searchValue.value.endAt.setMinutes(59);
  searchValue.value.endAt.setSeconds(59);
  searchValue.value.endAt = moment(searchValue.value.endAt).format('yyyy-MM-DD HH:mm:ss');
  radio.value = '';
  search();
};
/**
 * 搜索点击事件
 */
const search = async () => {
  if (moment(searchValue.value.startAt).diff(moment().format('YYYY-MM-DD HH:mm:ss')) >= 0) {
    ElMessage.error('开始时间不能晚于当前日期');
    searchValue.value.startAt = '';
  } else {
    if (searchValue.value.startAt !== '' && searchValue.value.endAt !== '') {
      if (moment(searchValue.value.startAt).diff(moment(searchValue.value.endAt)) <= 0) {
        searchValue.value.page = 1;
        rquestInvoiceList();
      } else {
        ElMessage.error('结束时间不能早于开始时间');
        searchValue.value.endAt = '';
      }
    } else {
      searchValue.value.page = 1;
      rquestInvoiceList();
    }
  }
  console.log('搜索', searchValue.value);
  searchValue.value.page = 1;
};
/**
 * 点击查看
 */
const invoiceId = ref(0);
const invoiceLook = (item: any) => {
  showInvoice.value = true;
  mask.value = true;
  if (item.invoiceUrl) {
    fileList.value[0] = {
      name: '发票',
      url: item.invoiceUrl,
    };
  }
  invoiceDate.value = {
    orderSn: item.orderSn,
    type: item.type,
    riseType: item.riseType,
    invoiceHeader: item.invoiceHeader,
    status: item.status,
    createdAt: item.createdAt,
    createPerson: item.createPerson,
    phone: item.phone,
    email: item.email,
    price: item.price,
  };
  console.log('查看', item);
  invoiceId.value = item.id;
};
// 点击上传
const uploadFile = (item: any) => {
  uploadShow.value = true;
  mask.value = true;
  console.log('123123', item);
  console.log(item);
  invoiceDate.value = {
    orderSn: item.orderSn,
    type: item.type,
    riseType: item.riseType,
    invoiceHeader: item.invoiceHeader,
    status: item.status,
    createdAt: item.createdAt,
    createPerson: item.createPerson,
    phone: item.phone,
    email: item.email,
    price: item.price,
  };
  invoiceId.value = item.id;
};

const fileList = ref<UploadUserFile[]>([]);
const handleChange = (file: any) => {
  console.log('123', file);
};
/**
 * 查看确认
 */

let loading = ref(false); //设置记录时间，用于防抖
let timer = ref(); //设置记录时间，用于防抖
const invoiceSure = () => {
  clearTimeout(timer);
  timer = setTimeout(async () => {
    loading.value = true;
    const formimgs = new FormData();
    console.log(fileList.value[0].raw);
    formimgs.append('image', fileList.value[0].raw);
    const blob = new Blob([JSON.stringify(invoiceId.value)], {
      type: 'application/json;charset=utf-8',
    });
    formimgs.append('id', blob);
    new Promise((resolve, reject) => {
      RequestInvoiceUpload(formimgs)
        .then(() => {
          resolve('上传成功');
          rquestInvoiceList();
          maskBtn1();
          ElMessage.success('上传成功');
          loading.value = false;
        })
        .catch(() => {
          reject('上传失败');
          ElMessage.error('上传失败！');
          loading.value = false;
        });
    });
  }, 500);
};
/**
 * 遮罩层数据
 */
const maskBtn1 = () => {
  mask.value = false;
  showInvoice.value = false;
  uploadShow.value = false;
  fileList.value = [];
};
</script>
<style lang="scss" scoped>
@import '@/assets/css/plateform/Article/Content.css';
@import '@/assets/css/plateform/Shop/GoodsManage.css';

.link:hover {
  color: #409eff !important;
}

::v-deep .el-upload-dragger {
  width: 100% !important;
}

:deep(.el-upload) {
  height: auto !important;
}

.content_box ::v-deep .el-upload.is-drag {
  width: 100%;
  height: 100%;
}

.nav_ul {
  width: 100%;
  .nav_li {
    width: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .nav_lis {
    position: relative;
    cursor: pointer;
    .number {
      padding: 0 5px;
      display: block;
      line-height: 16px;
      height: 16px;
      color: #fff;
      font-size: 12px;
      background: #409eff;
      border-radius: 8px;
      position: absolute;
      top: 2px;
      right: -12px;
    }
  }
  .navlist {
    .number {
      background: #116cf8;
      color: #fff;
    }
  }
}
.look_invoice {
  width: 50%;
  height: 60%;
  position: fixed;
  top: 20%;
  left: 25%;
  z-index: 99;
  background: #fff;
}
.look_invoice1 {
  width: 500px;
  height: 400px;
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -200px;
  margin-left: -250px;
  z-index: 99;
  background: #fff;
}
.el-table .check_table {
  background: pink !important;
}

.table {
  height: calc(100% - v-bind(tablelistHeight)) !important;
}
::v-deep .el-table--fit {
  height: calc(100% - 100px) !important;
}
.table :deep(.el-table__cell) {
  text-align: center;
}
.el-form-item :deep(.el-input-group__prepend) {
  width: 10px;
  background-color: #116cf8;
  color: #fff;
}
.el-table .warning-row {
  background: #f2f7fc;
}
</style>
